package pbc.gx.SaveJson.kafka.service;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@SuppressWarnings("ALL")
@Slf4j
@RestController
@CrossOrigin
public class RedisValues {
    private final RedisTemplate redisTemplate;

    public RedisValues(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @RequestMapping("/redisValues")
    public List redisValues() {
        Set<byte[]> keysB = (Set<byte[]>) redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                return redisConnection.keys(redisTemplate.getKeySerializer().serialize("dev:000000000000000000??"));
            }
        });
        RedisSerializer serializer = redisTemplate.getKeySerializer();
        Set<byte[]> keysBS = new TreeSet<byte[]>(new Comparator<byte[]>() {
            @Override
            public int compare(byte[] o1, byte[] o2) {
                String s1 = serializer.deserialize(o1).toString();
                String s2 = serializer.deserialize(o2).toString();
                Long l1 = Long.parseLong(s1.split(":")[1]);
                Long l2 = Long.parseLong(s2.split(":")[1]);
                return l1.compareTo(l2);
            }
        });
        keysBS.addAll(keysB);
        assert keysB != null;
        Iterator<byte[]> iter = keysBS.iterator();
        List list = redisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                while (iter.hasNext()) {
                    redisConnection.hGetAll(iter.next());
                }
                return null;
            }
        });
        return list;
    }
}
